package com.mvd.app.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.mvd.app.R;
import com.mvd.app.adapter.WaiJianResultAdapter2;
import com.mvd.app.application.BaseApplication;
import com.mvd.app.commons.CommonUtils;
import com.mvd.app.commons.PDALogUtils;
import com.mvd.app.commons.SharedPreferencesUtils;
import com.mvd.app.commons.UtilsLog;
import com.mvd.app.model.CarsInforModel;
import com.mvd.app.model.City;
import com.mvd.app.model.Group;
import com.mvd.app.model.Item_1Model;
import com.mvd.app.model.Item_2Model;
import com.mvd.app.model.WaiJianAddRecordModel;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;

import static com.mvd.app.application.BaseApplication.myChoiceModelList;
import static com.mvd.app.application.BaseApplication.mycar_checkItemlList;
import static com.mvd.app.application.BaseApplication.waiJianPhoto_buhege_List;

//外检结果
public class WaiJianResultActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    private ExpandableListView expandableListView;
    private List<Group> groupList = new ArrayList<Group>();
    private WaiJianResultAdapter2 adapter;
    private List<Object> gridList = new ArrayList<Object>();

    private WaiJianResultActivity instances = null;

    private String carNo = null;//车牌号码
    private String PlateType = null;//号牌种类类型
    private String cartype = null;//车辆类型

    CarsInforModel carsInforModel;
    //    private List<CheckItemModel> mycar_checkItemlList = new ArrayList<>();//获取当前车辆需要的人工检验项目
    List<Item_2Model> Item_2Model_list = new ArrayList<>();//Code2去重后的所有数据
//    List<MyChoiceModel> myChoiceModelList = new ArrayList<>();//Code2选择的列表


    List<WaiJianAddRecordModel> WaiJianAddRecordModelList = new ArrayList<>();//外检增加记录list

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wai_jian_result);
        ButterKnife.bind(this);

        setBackBtn();
        setTopTitle("检测项目");
        waiJianPhoto_buhege_List = new ArrayList<>();
        String logStrf = "\n" + "onCreate-----检测项目---外检结果--BuWaiJianResultActivity---" + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrf.getBytes());

        instances = this;
        carsInforModel = (CarsInforModel) getIntent().getSerializableExtra("WaiJianPhotoActivity_CarsInforModel");

        BaseApplication.BaseApplication_buHeGeModel3List = new ArrayList<>();

        //获取需要检测的人工检验项目接口
//        getData();
        //车牌号码
        if (!TextUtils.isEmpty(carsInforModel.getPlateRegion()) && !TextUtils.isEmpty(carsInforModel
                .getPlateNO())) {
            carNo = carsInforModel.getPlateRegion() + carsInforModel.getPlateNO();
        }
        //号牌类型
        if (!TextUtils.isEmpty(carsInforModel.getPlateTypeName())) {
            PlateType = String.valueOf(carsInforModel.getPlateTypeName());
        }
        //车辆类型
        if (!TextUtils.isEmpty(carsInforModel.getType())) {
            cartype = String.valueOf(carsInforModel.getType());
        }
        setUpViews();
        setUpListeners();

//        init();
        BaseApplication.IsAllSelect = true;

        setRightTxt("完成", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //封装数据list
                setDataModel();
//                if (WaiJianAddRecordModelList != null && WaiJianAddRecordModelList.size() > 0) {
                //上传数据
                uploadDataByWaiJianItem();
//                }else {
//                    Toast.makeText(instances, "没有选择相关项目", Toast
//                            .LENGTH_LONG).show();
//                }
            }
        });
//        for (int i = 0; i < mycar_checkItemlList.size(); i++) {
//            UtilsLog.e("外检结果==mycar_checkItemlList===" + mycar_checkItemlList.get(i).toString());
//        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        UtilsLog.e("IsAllSelect===" + BaseApplication.IsAllSelect);
        if (BaseApplication.BaseApplication_buHeGeModel3List != null
                && BaseApplication.BaseApplication_buHeGeModel3List.size() > 0) {
            String upload_code_str_names = "";
            for (int i = 0; i < BaseApplication.BaseApplication_buHeGeModel3List.size(); i++) {
                upload_code_str_names = upload_code_str_names + "," + BaseApplication.BaseApplication_buHeGeModel3List.get(i).getName3();
            }
            UtilsLog.e("BaseApplication_buHeGeModel3List==一二级目录==upload_code_str_names="+upload_code_str_names);
            UtilsLog.e("BaseApplication_buHeGeModel3List==一二级目录=原始数据=" + BaseApplication.BaseApplication_buHeGeModel3List.toString());
        } else {
            UtilsLog.e("BaseApplication_buHeGeModel3List==一二级目录==nullllll=");
        }
        init();
//        if (BaseApplication.IsAllSelect == false) {
//
//        } else {
//            //第三级列表是全选的
//            init();
//        }
    }

    private void setUpViews() {
        expandableListView = (ExpandableListView) findViewById(R.id.ex);
    }

    private void setUpListeners() {
        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
//                int i = groupList.get(groupPosition).getCityList().size();
                City city = groupList.get(groupPosition).getCityList().get(childPosition);
//                if (i<groupPosition) {
                city.changeChecked();
                adapter.notifyDataSetChanged();
                reFlashGridView();
//                } else {
//                    Toast.makeText(BuWaiJianResultActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
//                }
                UtilsLog.e("city==" + city.toString());
                Intent intent = new Intent(instances, WaiJianThirdResultActivity.class);
                intent.putExtra("w_code1", city.getCode1());
                intent.putExtra("w_code2", city.getCode2());
                intent.putExtra("w_Flag", city.getFlag());
                startActivity(intent);
                UtilsLog.e("groupList==" + groupList.get(groupPosition).toString());
//                for (int i = 0; i < groupList.get(groupPosition).getCityList().size(); i++) {
//                    UtilsLog.e("groupList=groupList=(" + i + ")===" + groupList.get(i).toString());
//                    String Code2 = groupList.get(groupPosition).getCityList().get(i).getCode2();
//                    boolean isCheck = groupList.get(groupPosition).getCityList().get(i).isChecked();
//                    for (int j = 0; j < myChoiceModelList.size(); j++) {
//                        if (Code2.equals(myChoiceModelList.get(j).getCode2())) {
//                            myChoiceModelList.get(j).setChecked(isCheck);
//                            if (isCheck) {
//                                myChoiceModelList.get(j).setCode_values("1");
//                            } else {
//                                myChoiceModelList.get(j).setCode_values("2");
//                            }
//                        }
//                    }
//                }

                String Code2 = city.getCode2();
                boolean isCheck = city.isChecked();

                for (int i = 0; i < myChoiceModelList.size(); i++) {
                    if (Code2.equals(myChoiceModelList.get(i).getCode2())) {
                        myChoiceModelList.get(i).setChecked(isCheck);
                        if (isCheck) {
                            myChoiceModelList.get(i).setCode_values("1");
                        } else {
                            myChoiceModelList.get(i).setCode_values("2");
                        }
                    }
//                    UtilsLog.e("myChoiceModelList=groupList=(" + i + ")===" + myChoiceModelList.get(i).toString());
                }
//                waiJianPhoto_buhege_List=myChoiceModelList;

                return false;
            }
        });
    }

    //    int groupPosition_m = 0, childPosition_m = 0;
    int FLAG = 0;//不合格2  合格1  不适用 0
    private WaiJianResultAdapter2.MyClickListener mListener = new WaiJianResultAdapter2.MyClickListener() {

        @Override
        public void myOnClick(int groupPosition, int childPosition, View v, int flag) {
//            groupPosition_m = groupPosition;
//            childPosition_m = childPosition;
            FLAG = flag;
            if (flag == 0) {
                //不适用 0
                UtilsLog.e("000000000000==");
                reInitDataAdapter(groupPosition, childPosition, "0");

                String logStr = "\n" + "外检不合格项目-增加外检记录接口--myOnClick" +
                        "\n" + "groupPosition::" + groupPosition + "\n" +
                        "childPosition::" + childPosition + "\n" +
                        "flag::" + flag + "\n" + "00000" + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());

            } else if (flag == 1) {
                //合格1
                UtilsLog.e("11111111111111==");
                reInitDataAdapter(groupPosition, childPosition, "1");
                String logStr = "\n" + "外检不合格项目-增加外检记录接口--myOnClick" +
                        "\n" + "groupPosition::" + groupPosition + "\n" +
                        "childPosition::" + childPosition + "\n" +
                        "flag::" + flag + "\n" + "11111" + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
            } else if (flag == 2) {
                //不合格2
                UtilsLog.e("22222222==");
                reInitDataAdapter(groupPosition, childPosition, "2");
                String logStr = "\n" + "外检不合格项目-增加外检记录接口--myOnClick" +
                        "\n" + "groupPosition::" + groupPosition + "\n" +
                        "childPosition::" + childPosition + "\n" +
                        "flag::" + flag + "\n" + "22222" + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                City city = groupList.get(groupPosition).getCityList().get(childPosition);
                Intent intent = new Intent(instances, WaiJianThirdResultActivity.class);
                intent.putExtra("w_code1", city.getCode1());
                intent.putExtra("w_code2", city.getCode2());
                intent.putExtra("w_Flag", city.getFlag());
                startActivity(intent);
            }
        }
    };


    private void reInitDataAdapter(int groupPosition, int childPosition, String Flag) {
        City adapterCity;
        Group adapterGroup;
        adapterGroup = new Group();
        adapterGroup.setName(groupList.get(groupPosition).getName());
        adapterGroup.setName1(groupList.get(groupPosition).getName1());
        adapterGroup.setCode1(groupList.get(groupPosition).getCode1());
        adapterGroup.setID(groupList.get(groupPosition).getID());
        adapterGroup.setChecked(true);

        adapterCity = new City();
        adapterCity.setFlag(Flag);
        adapterCity.setID(groupList.get(groupPosition).getCityList().get(childPosition).getID());
        adapterCity.setName(groupList.get(groupPosition).getCityList().get(childPosition).getName());
        adapterCity.setName1(groupList.get(groupPosition).getCityList().get(childPosition).getName1());
        adapterCity.setName2(groupList.get(groupPosition).getCityList().get(childPosition).getName2());
        adapterCity.setName3(groupList.get(groupPosition).getCityList().get(childPosition).getName3());
        adapterCity.setCode1(groupList.get(groupPosition).getCityList().get(childPosition).getCode1());
        adapterCity.setCode2(groupList.get(groupPosition).getCityList().get(childPosition).getCode2());
        adapterCity.setCode3(groupList.get(groupPosition).getCityList().get(childPosition).getCode3());
        adapterCity.setChecked(true);
        adapterCity.setIsChange(1);
        groupList.get(groupPosition).getCityList().set(childPosition, adapterCity);
        adapterGroup.setCityList(groupList.get(groupPosition).getCityList());
        groupList.set(groupPosition, adapterGroup);
        adapter.notifyDataSetChanged();
        UtilsLog.e("myChoiceModelList--HHHHHHH==" + adapterCity.getName2());
        for (int i = 0; i < mycar_checkItemlList.size(); i++) {
            if (adapterCity.getName2().equals(mycar_checkItemlList.get(i).getName2())) {
                mycar_checkItemlList.get(i).setFlag(Flag);
            }
        }
        String logStr = "\n" + "外检不合格项目-增加外检记录接口--reInitDataAdapter" +
                "\n" + "groupList::" + groupList.toString() + "\n" +
                "Flag" + Flag + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
    }

    private void setDataModel() {
        if (WaiJianAddRecordModelList != null) {
            WaiJianAddRecordModelList.clear();
        }
        WaiJianAddRecordModelList = new ArrayList<>();
        if (groupList != null && groupList.size() > 0) {
            for (int i = 0; i < groupList.size(); i++) {
                List<City> cityList = groupList.get(i).getCityList();
                for (int j = 0; j < cityList.size(); j++) {
//                    if (cityList.get(j).getIsChange() == 1) {
                    WaiJianAddRecordModel model = new WaiJianAddRecordModel();
                    model.setDataType("F1_Record");
                    model.setDetection_ID(String.valueOf(carsInforModel.getID()));
                    model.setGUID(carsInforModel.getGUID());
                    model.setTimes(carsInforModel.getTimes());
                    model.setUnqualified_Code1(cityList.get(j).getCode1());
                    model.setUnqualified_Code2(cityList.get(j).getCode2());
                    model.setVerdict(cityList.get(j).getFlag());
                    WaiJianAddRecordModelList.add(model);
//                    }
                }
            }
        }
        String logStr = "\n" + "外检不合格项目-增加外检记录接口--setDataModel" +
                "\n" + "WaiJianAddRecordModelList::" + WaiJianAddRecordModelList.toString() + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        UtilsLog.e("WaiJianAddRecordModelList=222=" + WaiJianAddRecordModelList.toString());
    }


    public static void setListViewHeightBasedONChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    private void init() {
        groupList = new ArrayList<Group>();
        gridList = new ArrayList<Object>();
        Item_2Model_list = new ArrayList<>();
        initData2();
        for (int i = 0; i < groupList.size(); i++) {
            UtilsLog.e("groupList===" + groupList.get(i).toString());
        }
        adapter = new WaiJianResultAdapter2(this, groupList, mListener);
        expandableListView.setAdapter(adapter);
        reFlashGridView();
        //全部展开
        for (int i = 0; i < groupList.size(); i++) {
            expandableListView.expandGroup(i);
        }
/*
全部展开
        int groupCount = expandableListView.getCount();
        for (int i=0; i<groupCount; i++) {
            expandableListView.expandGroup(i);
        };*/
    }

    public void reFlashGridView() {
        gridList.clear();
        for (Group group : groupList) {
            if (group.isChecked()) {
                gridList.add(group);
            } else {
                for (City city : group.getCityList()) {
                    if (city.isChecked()) {
                        gridList.add(city);
                    }
                }
            }
        }
    }

    void initData2() {
        List<Item_1Model> Item_1Model_list = new ArrayList<>();
        Item_1Model item_1 = null;
        for (int i = 0; i < mycar_checkItemlList.size(); i++) {
//            UtilsLog.e("mycar_checkItemlList===" + mycar_checkItemlList.get(i).toString());
            item_1 = new Item_1Model();
            item_1.setID(mycar_checkItemlList.get(i).getID());
            item_1.setCode1(mycar_checkItemlList.get(i).getCode1());
            item_1.setName1(mycar_checkItemlList.get(i).getName1());
            Item_1Model_list.add(item_1);
        }
        for (int k = 0; k < Item_1Model_list.size() - 1; k++) {
            for (int j = Item_1Model_list.size() - 1; j > k; j--) {
                if (Item_1Model_list.get(j).getCode1().equals(Item_1Model_list.get(k).getCode1())) {
                    Item_1Model_list.remove(j);
                }
            }
        }

        Item_2Model item_2 = null;
        for (int i = 0; i < mycar_checkItemlList.size(); i++) {
            item_2 = new Item_2Model();
            item_2.setID(mycar_checkItemlList.get(i).getID());
            item_2.setCode1(mycar_checkItemlList.get(i).getCode1());
            item_2.setCode2(mycar_checkItemlList.get(i).getCode2());
            item_2.setName2(mycar_checkItemlList.get(i).getName2());
            item_2.setName3(mycar_checkItemlList.get(i).getName3());
            item_2.setFlag(mycar_checkItemlList.get(i).getFlag());
            Item_2Model_list.add(item_2);
        }
        for (int k = 0; k < Item_2Model_list.size() - 1; k++) {
            for (int j = Item_2Model_list.size() - 1; j > k; j--) {
                if (Item_2Model_list.get(j).getCode2().equals(Item_2Model_list.get(k).getCode2())) {
                    Item_2Model_list.remove(j);
                }
            }
        }
//        for (int i = 0; i < myChoiceModelList.size(); i++) {
//            String Code2 = myChoiceModelList.get(i).getCode2();
//            for (int j = 0; j < Item_2Model_list.size(); j++) {
//                if (Code2.equals(Item_2Model_list.get(j).getCode2())) {
//                    myChoiceModelList.get(i).setCode_values("1");
//                }
//            }
//        }
        for (int i = 0; i < Item_1Model_list.size(); i++) {
            Group group = new Group();
            group.setID(Item_1Model_list.get(i).getID());
            group.setCode1(Item_1Model_list.get(i).getCode1());
            group.setName(Item_1Model_list.get(i).getName1());
            group.setChecked(false);

            List<City> cityList = new ArrayList<City>();

            if (i < Item_2Model_list.size()) {
                for (int j = 0; j < Item_2Model_list.size(); j++) {

                    if (group.getCode1().equals(Item_2Model_list.get(j).getCode1())) {
                        City city = new City();
                        city.setID(Item_2Model_list.get(j).getID());
                        city.setCode1(Item_2Model_list.get(j).getCode1());
                        city.setCode2(Item_2Model_list.get(j).getCode2());
                        city.setName2(Item_2Model_list.get(j).getName2());
                        city.setName3(Item_2Model_list.get(j).getName3());
                        city.setName(Item_2Model_list.get(j).getName2());
                        if (!TextUtils.isEmpty(Item_2Model_list.get(j).getFlag()) && Item_2Model_list.get(j).getFlag() != "null") {
                            city.setFlag(Item_2Model_list.get(j).getFlag());
                        } else {
                            city.setFlag("0");
                        }

                        city.setIsChange(0);
                        if (Item_2Model_list.get(j).getFlag() != null) {
//                            Flag --0:不检测 1：检测
                            if (Integer.valueOf(Item_2Model_list.get(j).getFlag()) == 0) {
                                city.setChecked(false);
                            } else {
                                city.setChecked(true);
                            }
                        }
//                        city.setChecked(true);
                        cityList.add(city);
                        city.addObserver(group);
                        group.addObserver(city);
                    }
                }
            }
            if (cityList != null && cityList.size() > 0) {
                group.setCityList(cityList);
            }
            groupList.add(group);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
        String logStrf = "\n" + "onDestroy-----检测项目---外检结果--BuWaiJianResultActivity---" + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrf.getBytes());
        instances = null;
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    //外检不合格项目-增加外检记录接口
    private void uploadDataByWaiJianItem() {
        Gson gson = new Gson();
        String jsonStr = gson.toJson(WaiJianAddRecordModelList);
        UtilsLog.e("uploadDataByWaiJianItem---jsonStr==" + jsonStr);
        UtilsLog.e("uploadDataByWaiJianItem---url==" + SharedPreferencesUtils.getIP(this) + WAIJIAN_ADD_RECORED);
        String logStr = "\n" + "外检不合格项目-增加外检记录接口--uploadDataByWaiJianItem--请求" +
                "\n" + "URL::" + SharedPreferencesUtils.getIP(instances) +
                WAIJIAN_ADD_RECORED + "\n" + "JSON::" + jsonStr + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        OkGo.<String>post(SharedPreferencesUtils.getIP(this) + WAIJIAN_ADD_RECORED).tag(this)
                .upJson(jsonStr)
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        CommonUtils.showLoadingDialog(instances, "加载中...");
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        UtilsLog.e("uploadDataByWaiJianItem-result==" + result);
                        String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\", "");
                        UtilsLog.e("uploadDataByWaiJianItem-newResult==" + newResult);
                        CommonUtils.hideLoadingDialog(instances);
                        if ("ok".equalsIgnoreCase(newResult)) {
                            Toast.makeText(instances, "提交成功", Toast.LENGTH_LONG).show();
                            Intent intent = new Intent();
                            intent.putExtra("waiJianPhoto_buhege_List", (Serializable) mycar_checkItemlList);
                            instances.setResult(500, intent);
                            instances.finish();
                        } else {
                            Toast.makeText(instances, "提交失败，请重试", Toast
                                    .LENGTH_LONG).show();
                        }
                        String logStrf = "\n" + "外检不合格项目-增加外检记录接口--uploadDataByWaiJianItem--请求成功" +
                                "\n" + "result::" + response.body();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrf.getBytes());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        UtilsLog.e("uploadDataByWaiJianItem-onError==" + response.body());
                        CommonUtils.hideLoadingDialog(instances);
                        String logStr = "\n" + "外检不合格项目-增加外检记录接口--uploadDataByWaiJianItem-onError-失败" +
                                "\n" + "result::" + response.body();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                    }
                });
    }

}
